<template>
  <span>
    <a-dropdown @visibleChange="visibleChange" :disabled="props.disabled">
      <a class="ant-dropdown-link" @click.prevent v-if="buttonType == 'button'">
        更多操作
        <DownOutlined />
      </a>
      <a class="ant-dropdown-link" @click.prevent v-else>
        <ellipsis-outlined />
      </a>
      <template #overlay>
        <a-menu>
          <a-menu-item
            @click="onClick(item.key,item.loading)"
            :key="item.key"
            v-for="item in routeNameList"
          >
            <a-button type="link" :loading="item.loading">
              {{ item.name }}
            </a-button>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <MaterialsModule
      v-if="visibe"
      ref="materials"
      :material_type="props.materialType"
      :data="{ material_url: materialUrl, autoName: video_name }"
      @onSuccess="() => (saveVisible = false)"
      :visible="saveVisible"
      @onCancel="saveVisible = false"
    />
    <BatchCollect ref="BatchCollectRef"  v-if="visibe" :articles="chooseTextArticle"></BatchCollect>
  </span>
</template>
<script setup>
import { DownOutlined, EllipsisOutlined } from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { computed, ref } from "vue";
import { message } from "ant-design-vue";
import dayjs from 'dayjs'
import store from "@/store/index.js";
import MaterialsModule from "@/views/shotstack/components/MaterialsModule/materialLibraryModal.vue";
// 保存到文案库弹窗
import BatchCollect from "@/views/shotstack/AiCreation/components/batchCollect.vue";

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false, 
  },
  buttonType:{
    type:String,
    default:'button'
  },
  routeNames: {
    type: Array,
    default: () => [
      {
        name: "视频去水印",
        key: "VideoRemoveSignIndex",
        loading:false,
      },
      {
        name: "视频去字幕",
        key: "VideoRemoveSubtitlesIndex",
        loading:false,
      },
      {
        name: "视频提取文案",
        key: "AddVideoToText",
        loading:false,
      },
      {
        name: "视频提取音频",
        key: "VideoExtractAudioIndex",
        loading:false,
      },
      {
        name: "视频裁剪",
        key: "VideoCroppingIndex",
        loading:false,
      },
      {
        name: "视频拆分",
        key: "AddVideoIntelligentSplit",
        loading:false,
      },
      {
        name: "视频去除音频",
        key: "VideoRemoveAudioIndex",
        loading:false,
      },
      {
        name: "视频翻译",
        key: "VideoTranslateIndex",
        loading:false,
      },
      {
        name: "视频生成字幕",
        key: "VideoGenerateSubtitlesIndex",
        loading:false,
      },
      {
        name: "存素材库",
        key: "saveToMaterial",
        loading:false,
      },
      {
        name: "存文案库",
        key: "saveToText",
        loading:false,
      },
      {
        name: "下载",
        key: "download",
        loading:false,
      },
    ],
  },
  excludeNames: {
    type: Array,
    default: () => [], 
  },
  data: {
    type: Object,
    default: () => ({}),
  },
  //素材类型
  materialType: {
    type: String,
    default: "video",
  },
  extraName: {
    type: Object,
    default: ()=>null, 
  }
});
let visibe = ref(false);
const route = useRoute();
const routeNameList = computed(() => {
  let currentRoute = route.name;
  let list = props.routeNames.filter((item) => item.key !== currentRoute);
  let exList = list.filter(item=>!props.excludeNames.includes(item.key))
  let fList = exList.filter((item) => {
    if (props.materialType == "text") {
      return item.key !== "saveToMaterial";
    }else{
      return item.key!== "saveToText"; 
    }
  });
  if(props.extraName){
    fList.push(props.extraName)
  }
  return fList;
});
let saveVisible = ref(false);
let materialUrl = computed(() => {
  return  props.data?.media_url || props.data?.after_url || props.data?.material_url || props.data?.video_url;
});
let video_name = computed(() => {
  return '素材'+ '_' + dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
})
let BatchCollectRef = ref(null);

// 保存至文案库需要的数据
const chooseTextArticle = ref([]);
const router = useRouter();

const visibleChange = (e)=>{
  visibe.value = e;
  
}
// 下载素材逻辑
const dowload = async (loading) => {
  if(props.materialType == 'text'){
    let content = props.data?.contents || props.data?.content;
    downloadStringAsFile(content);
    return;
  }
  const videoUrl = materialUrl.value;
  const filename =
    "素材" + "_" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
  const fileUrl = videoUrl;
  loading = true;
  let blob = null;
  try {
    const response = await fetch(fileUrl); // 获取视频链接
    blob = await response.blob(); // 将响应转为 Blob
  } catch (e) {
    message.error("视频链接下载错误");
    loading = false;
    return;
  }

  const url = window.URL.createObjectURL(blob); // 创建一个 blob URL
  const link = document.createElement("a");
  link.href = url; // 设置 href 为 blob URL
  link.download = filename; // 可选，设置下载时的文件名
  document.body.appendChild(link);
  link.click(); // 模拟点击下载
  loading = false;
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url); // 清理
};
// 下载文案逻辑
function downloadStringAsFile(content) {
  const filename =
    "文案" + "_" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
  // 创建一个 Blob 对象
  const blob = new Blob([content], { type: 'text/plain' });
  
  // 创建一个临时的 <a> 元素
  const anchor = document.createElement('a');
  anchor.download = filename; // 设置下载的文件名
  anchor.href = URL.createObjectURL(blob); // 创建对象 URL
  
  // 触发点击事件，开始下载
  anchor.click();
  
  // 释放对象 URL，避免内存泄漏
  URL.revokeObjectURL(anchor.href);
}
// 路由带数据跳转逻辑
const handleRouteMethod = (name) => {
  // 处理几个特殊应用的跳转
  let dispatchMethod = [
    {
      key: "AddVideoIntelligentSplit",
      dispatchName: "setSceneCreationSubtileTitles",
    },
    {
      key: "AddVideoToText",
      dispatchName: "setExtractTextData",
    },
  ];
  // 处理各个应用素材的资源链接名称不一样的问题
  let material_data = { ...props.data, material_url: materialUrl.value };
  if (dispatchMethod.find((item) => item.key === name)) {
    store.dispatch(
      dispatchMethod.find((item) => item.key === name).dispatchName,
      material_data
    );
    router.push({ name });
  } else {
    store.dispatch("setApplicationMaterialData",material_data);
  }
  router.push({ name });
};
// 处理打开素材库和文本库的逻辑
const showOpenMaterialModal = (name) => {
  if (props.materialType == "text") {
    chooseTextArticle.value = [{title:video_name.value, content:props.data?.contents}];
    BatchCollectRef.value.showModal();
  }else{
    saveVisible.value = true; 
  }
  
};
const isOpenModal = (name) => {
  return ["saveToMaterial", "saveToText"].includes(name);
};
const onClick = async (name,loading) => {
  if (name == "download") {
    return dowload(loading);
  }
  if (isOpenModal(name)) {
    return showOpenMaterialModal(name);
  }
  handleRouteMethod(name);
};
</script>
<style lang="less" scoped></style>
